const request = require('request'),
    wechatApi = require('../config/config').wechatApi,
    db = require('../config/db');

/**
 * @author:ares
 * @datetime:2018/4/4 12:52
 * @description: 通过授权code换取网页授权的access_token
 * @param {string} code   用户授权后返回的code
 * @returns {Promise}
 */
function getWebAuthAccessToken(code) {
    let reqUrl = wechatApi.webAuthAccessTokenApiPrefix + code + wechatApi.webAuthAccessTokenApiSuffix,
        options = {
            method: 'get',
            url: reqUrl
        };
    console.log('>> 通过code换取网页授权access_token的地址 <<',options.url);
    return new Promise((resolve, reject) => {
        request(options, function (err, res, body) {
            if (res) {
                let result = JSON.parse(body);
                //已获取openid,code还没过期
                if (result.errcode && result.errcode == '40163'){
                    codeUsed(resolve,code);
                }
                //正常获取openid
                else if (result.openid){
                    console.log('>> 网页授权信息 <<',body)
                    newOrUpdateUserinfo(result,code);
                    resolve(body);
                }
            } else {
                reject(err);
            }
        })
    })
}


/**
 * @author: ares
 * @date: 2018/4/12 12:53
 * @description: 插入或更新用户对应的openid,code,access_token
 * @param {object}result     获取网页授权的结果
 * @param {string} code      获取access_token和openid的参数
 */
function newOrUpdateUserinfo(result,code) {
    let fieldsArr = ['openid','code','webtoken'],
        valueArr = [[result.openid,code,result.access_token]],
        insertInfo = db.buildInsertStr('user_info',fieldsArr,valueArr),
        updateInfo = db.buildUpdateStr('user_info',[
            {field:'code',value:code},
            {field:'webtoken',value:result.access_token}
        ]),
        queryOpenid = db.buildSelectStr('user_info',null,[{
            field:'openid',
            operator:'=',
            value:result.openid
        }]);
    db.query(queryOpenid).then(res => {
        if (res.length){
            db.query(updateInfo).then(rows => {
                console.log('>> 更新code和access_token <<',rows)
            }).catch(err => {
                console.log(err)
            })
        }else {
            db.query(insertInfo).then(rows => {
                console.log('>> 插入openid,code和access_token <<',rows)
            }).catch(err => {
                console.log(err)
            })
        }
    }).catch(err => {
        console.log(err)
    })
}

/**
 * @author: ares
 * @date: 2018/4/12 12:52
 * @description: 已经获取access_token和openid,并且code还未过期
 * @param {function}resolve   promise的参数
 * @param {string} code       获取access_token和openid的参数
 */
function codeUsed(resolve,code) {
    let getOpenid = db.buildSelectStr('user_info',null,[{
            field:'code',
            operator:'=',
            value:code
        }]),
        params = {};
    db.query(getOpenid).then(res => {
        params.access_token = res[0].webtoken;
        params.openid = res[0].openid;
        console.log('>> params <<',params)
        resolve(JSON.stringify(params));
    }).catch(err => {
        console.log(err)
    })
}

module.exports = getWebAuthAccessToken;